<template>
  <span>
    <i class="el-icon-refresh"
       @click="openAsyncDialog">
    </i>
    <el-dialog title="同步设置"
               :visible.sync="showAsync"
               width="40%"
               append-to-body
               >
      <el-row>
        <el-col span="4">
          上传云端范围：
        </el-col>
        <el-col span="18">
          <el-checkbox-group v-model="checkedTypes" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="city in typeOptions" :label="city.value" :key="city.value">{{city.label}}</el-checkbox>
          </el-checkbox-group>
        </el-col>
      </el-row>
      
      <div style="margin:0 auto; text-align:center; width:100%; height:100px;padding-top:20px"> 
        <el-button type="primary" size="small"  @click="handleAsyncSetting">同步到个人云端<i class="el-icon-upload2 el-icon--right"></i></el-button>
        <el-button type="primary" size="small"  @click="handleAsyncTenantSetting">同步到组织云端<i class="el-icon-upload2 el-icon--right"></i></el-button>
        <el-button type="primary" size="small"   @click="handleAsyncDownloadSetting">同步个人设置到本地<i class="el-icon-download el-icon--right"></i></el-button>
        <el-button type="primary" size="small"   @click="handleAsyncDownloadTenantSetting">同步组织设置到本地<i class="el-icon-download el-icon--right"></i></el-button>
      </div>
    </el-dialog>
  </span>
</template>

<script>
import {saveOrUpdateSysUserSetting,saveSysUserSetting,querySysUserSetting} from '@/api/system/sysUserSettingApi';
import { mapGetters } from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';

export default {
  name: 'top-lock',
  data() {
    return {
      //选择同步范围
      checkedTypes: [],
      checkAll: false,
      typeOptions: [],

      box: false,
      form: {
        passwd: ''
      },
      // 请求参数区
      showAsync: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  created() {},
  mounted() {
    setTimeout(() => {
      this.getSysDict();
    }, 100);
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  props: [],
  methods: {
    /**
     * 获取系统字典参数
     */
    async getSysDict() {
      let dicData = await this.$params.getSysDict('["asyncSettings"]');
      this.typeOptions = dicData.asyncSettings;
    },
    /**
     * 同步范围设置爱
     */
    handleCheckedCitiesChange(value) {
      //console.log('==checkedTypes==',this.checkedTypes);
    },
    /**
     * 打开同步窗口
     */
    openAsyncDialog(){
      this.showAsync =  true;
    },
    /**
     * 同步到个人云端
     */
    handleAsyncSetting() { 
      this.$confirm('同步将覆盖旧数据，确定同步吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.showAsync =  false;
        const loading = this.$loading({
          lock: true,
          text: '请耐心等待,正在同步中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        });
        let allStoreList = this.$getAllStore();
        let settingList = []
        allStoreList.forEach(element => {
          this.checkedTypes.forEach(types => {
            if(element.name.indexOf(types) > 0){
              element.name = element.name.replace(this.userInfo.userId,this.userInfo.tenantId);
              settingList.push({
                ... element
              })
            }
          });
          //element.name
        });
        let allStore = JSON.stringify(settingList)
        allStoreList = [];
        settingList = [];

        this.reqParams.singleBody = {
          id: this.userInfo.userId,
          userName: this.userInfo.userName,
          realName: this.userInfo.realName,
          tenantId: this.userInfo.tenantId,
          personalSettingContent: allStore
        };

        this.commonData = reqCommonMsg(this.reqParams)
        saveOrUpdateSysUserSetting(this.commonData).then(() => {
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '同步成功!'
          });
          this.showAsync=false;
          loading.close();
        }, error => {
          this.$message({
            customClass:'zZindex',
            type: 'error',
            message: '操作失败!'
          });
          this.$console.log(error);
          loading.close();
        });
      }).catch(() => {});    
    },
    /**
     * 同步到组织云端
     */
    handleAsyncTenantSetting() { 
      this.$confirm('同步将覆盖组织设置，确定同步吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.showAsync =  false;
        const loading = this.$loading({
          lock: true,
          text: '请耐心等待,正在同步中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        });
        let allStoreList = this.$getAllStore();
        let settingList = [];
        allStoreList.forEach(element => {
          this.checkedTypes.forEach(types => {
            if(element.name.indexOf(types) > 0){
              element.name = element.name.replace(this.userInfo.userId,this.userInfo.tenantId);
              settingList.push({
                ... element
              })
            }
          });
          //element.name
        });
        let allStore = JSON.stringify(settingList)

        this.reqParams.singleBody = {
          id: this.userInfo.tenantId,
          userName: this.userInfo.userName,
          realName: this.userInfo.realName,
          tenantId: this.userInfo.tenantId,
          personalSettingContent: allStore
        };
        allStoreList = [];
        settingList = [];
        this.commonData = reqCommonMsg(this.reqParams)
        saveOrUpdateSysUserSetting(this.commonData).then(() => {
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '同步成功!'
          });
          this.showAsync=false;
          loading.close();
        }, error => {
          this.$message({
            customClass:'zZindex',
            type: 'error',
            message: '操作失败!'
          });
          this.$console.log(error);
          loading.close();
        });
      }).catch(() => {});       
    },
    
    /**
     * 同步到本地
     */
    handleAsyncDownloadSetting() {
      this.$confirm('同步将覆盖本地缓存，确定同步吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.showAsync =  false;
        const loading = this.$loading({
          lock: true,
          text: '请耐心等待,正在同步中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        });
 
        this.reqParams.singleBody ={
          id: this.userInfo.userId
        }
        this.commonData = reqCommonMsg(this.reqParams)
        querySysUserSetting(this.commonData).then(res => {
          //恢复本地localstorage
          let remotSetting = JSON.parse(res.data.body.singleBody.personalSettingContent);
          remotSetting.forEach(element => {
            if(element.name.indexOf(this.userInfo.userId) >= 0){
              this.$setStore({name: element.name, content: element.content});
            }
          });
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '同步成功!'
          });
          loading.close();
        }, error => {
          this.settingForm = {};
        });
      }).catch(() => {});       
    },
    /**
     * 同步租户设置到本地
     */
    handleAsyncDownloadTenantSetting() {
      this.$confirm('同步将覆盖本地缓存，确定同步吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.showAsync =  false;
        const loading = this.$loading({
          lock: true,
          text: '请耐心等待,正在同步中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        });
 
        this.reqParams.singleBody ={
          id: this.userInfo.tenantId
        }
        this.commonData = reqCommonMsg(this.reqParams)
        querySysUserSetting(this.commonData).then(res => {
          //恢复本地localstorage
          let remotSetting = JSON.parse(res.data.body.singleBody.personalSettingContent);
          remotSetting.forEach(element => {
            if(element.name.indexOf(this.userInfo.tenantId) >= 0){
              element.name = element.name.replace(this.userInfo.tenantId, this.userInfo.userId);
              this.$setStore({name: element.name, content: element.content});
            }
          });
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '同步成功!'
          });
          loading.close();
        }, error => {
          this.settingForm = {};
        });
      }).catch(() => {});       
    }
  },
  components: {}
};
</script>

<style lang="scss" scoped>
</style>
